package com.qk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.UserDto;
import com.qk.mapper.UserMapper;
import com.qk.pojo.User;
import com.qk.service.UserService;
import com.qk.vo.LoginResultVo;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 条件分页查询用户列表
     *
     * @param userDto
     */
    @Override
    public PageResult<User> getUsers(UserDto userDto) {
        // 开始分页
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());

        // 执行查询
        List<User> users = userMapper.getUsers(userDto);

        // 获取分页信息
        Page<User> pageInfo = (Page<User>) users;

        // 封装成 PageResult 对象
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }

    /**
     * 新增用户
     *
     * @param user
     */
    @Override
    public void addUser(User user) {
        // 设置创建时间和更新时间为当前时间
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+"123").getBytes()));  //对密码进行MD5加密
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    /**
     * 删除用户
     * @param ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    /**
     * 根据ID查询用户信息
     */
    @Override
    public User getById(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 修改用户信息
     */
    @Override
    public void updateUser(User user) {
        //1. 设置修改时间
        user.setUpdateTime(LocalDateTime.now());

        //2. 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex((user.getUsername() + "123").getBytes()));

        //3. 调用Mapper层更新用户信息
        userMapper.update(user);
    }

    /**
     * 根据角色查询用户信息
     * @param roleLabel
     * @return
     */
    @Override
    public List<User> getUsersByRoleLabel(String roleLabel) {
        return userMapper.getUsersByRoleLabel(roleLabel);
    }



}
